package com.world.cat.service.sys;

import com.world.cat.dao.sys.UserRoleDao;
import com.world.cat.model.sys.*;
import com.world.common.util.CollectionUtil;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Transactional
public class UserRoleService {
    private static final Logger logger = Logger.getLogger(UserRoleService.class);
    public static Map<String, UserRole> userRoleMap = new ConcurrentHashMap<>();

    @Resource
    private UserRoleDao userRoleDao;

    public List<UserRole> findUserRole(String userId) {
        return userRoleDao.findByUserId(userId);
    }

    //获取userid与角色的对应关系
    public static Map<String, Set<Role>> getUserIdRoleMap() {
        Map<String, Set<Role>> userIdRoleMap = new HashMap<>();
        Collection<UserRole> userRoles = userRoleMap.values();
        if (CollectionUtil.isNotEmpty(userRoles)) {
            for (UserRole userRole : userRoles) {
                Set<Role> roleSet = userIdRoleMap.get(userRole.getUserId());
                if (roleSet == null) {
                    roleSet = new HashSet<>();
                    userIdRoleMap.put(userRole.getUserId(), roleSet);
                }
                Role role = RoleService.roleIdRoleMap.get(userRole.getRoleId());
                if (role != null) {
                    roleSet.add(role);
                }
            }
        }
        return userIdRoleMap;
    }

    public void initUserRoleCache() {
        userRoleMap.clear();
        logger.info("初始化角色菜单关系数据开始--------------------------------");
        List<UserRole> os = userRoleDao.findAll();
        if (CollectionUtil.isNotEmpty(os)) {
            for (UserRole o : os) {
                userRoleMap.put(o.getId(), o);
            }
        }
        logger.info("初始化角色菜单关系数据结束--------------------------------");
    }
}
